﻿namespace CN2P.ServiceModel
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;

    [DataContract]
    public class CartModel
    {
        public CartModel()
        {
            this.Items = new List<CartItemModel>();
        }

        [DataMember(Name = "userId")]
        public string UserId { get; set; }

        [DataMember(Name = "totalValue")]
        public decimal TotalValue
        {
            get
            {
                if (this.Items.Count == 0)
                {
                    return 0m;
                }

                return this.Items.Sum(item => item.ProdPrice * item.Quantity);
            }
        }

        [DataMember(Name = "items")]
        public IList<CartItemModel> Items { get; set; }

        public bool HasProduct(string productId)
        {
            return this.Items.Any(item => item.ProdId == productId);
        }

        public OrderModel CreateOrder()
        {
            return new OrderModel
            {
                OrderId = Math.Abs(Guid.NewGuid().GetHashCode()).ToString(),
                UserId = this.UserId,
                TotalValue = this.TotalValue,
                OrderDate = DateTime.Now.ToString("yyyy-MM-dd"),
                Items = this.Items.Select(item => item.CreateOrderItem()).ToList()
            };
        }
    }
}
